package Util;/*
 *徐韬
 *2021/9/20
 *12:51
 */

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidUitl {
   private static  DruidDataSource ds;
    static  ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
   static{
       try {
           Properties properties = new Properties();
           InputStream resourceAsStream = DruidUitl.class.getResourceAsStream("/db.properties");
           properties.load(resourceAsStream);
           ds= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
       } catch (Exception e) {
           e.printStackTrace();
       }
   }
   public static Connection getConnection(){
       Connection connection = threadLocal.get();
       try {
           if(connection ==null){
               connection = ds.getConnection();
               threadLocal.set(connection);
           }
       } catch (SQLException e) {
           e.printStackTrace();
       }
       return connection;


   }
   public static void begin(){
       Connection connection = getConnection();
       try {
           connection.setAutoCommit(false);
       } catch (SQLException e) {
           e.printStackTrace();
       }
   }
   public static void comit(){
       Connection connection = getConnection();
       try {
           connection.commit();
       } catch (SQLException e) {

       }
   }
   public static void rollback(){
       Connection connection = getConnection();
       try {
           connection.rollback();
       } catch (SQLException e) {
           e.printStackTrace();
       }
   }
   public static void close(){
       Connection connection = getConnection();
       try {
           connection.close();
           threadLocal.remove();
       } catch (SQLException e) {
           e.printStackTrace();
       }
   }
}
